package com.simple.core.util;

import com.simple.core.entity.BaseEntity;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.util.Assert;

import java.io.Serializable;

/**
 * 全局雪花id生成器
 *
 * @author : mocun
 * @since : 2023/3/11
 */
public class SnowFlakeIdGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        if (o instanceof BaseEntity) {
            BaseEntity domain = (BaseEntity) o;
            Long id = domain.getId();
            if (id != null) {
                Assert.isTrue(id > 0, "id必须大于0");
                return id;
            }
        }
        return SnowFlakeUtils.nextId();
    }
}
